// Pavel Zolnikov[http://www.codeproject.com/script/profile/whos_who.asp?id=35980], 2002

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using VirusCleaner;

namespace VirusCleaner.Center
{
	/// <summary>
	/// Hooks into CreateProcessW API that is called from exporer (through shell32.dll).
	/// </summary>
	/// <remarks>
	/// Makes sure that no CREATE_NEW_CONSOLE flag set so all console output of apps started 
	/// by explorer goes into the Command Prompt Explorer Bar.
	/// </remarks>
	class CreateProcessHook : ApiInterceptor 
	{
		public CreateProcessHook()
			: base("shell32.dll","kernel32.dll","CreateProcessW",new CreateProcessFn(MyCreateProcess)) {}
		
		static bool MyCreateProcess(
			IntPtr	applicationName,   
			IntPtr	commandLine,       
			IntPtr	processAttributes, 
			IntPtr	threadAttributes,  
			Int32	inheritHandles,       
			Int32	creationFlags,      
			IntPtr	environment,       
			IntPtr	currentDirectory,  
			IntPtr	startupInfo,       
			IntPtr	processInformation )
		{
			Win32.STARTUPINFO si = (Win32.STARTUPINFO)Marshal.PtrToStructure(startupInfo,typeof(Win32.STARTUPINFO));

            //CommandBarObj bar = CommandBarObj.GetBarFromThreadId(Win32.GetCurrentThreadId());
            //if( bar != null && bar.Visible )
            //{
            //    creationFlags &= ~Win32.CREATE_NEW_CONSOLE;
            //    si.dwFlags &= ~0x400;//don't know what this flag is but its absence is necessary
            //}

			bool b = Win32.CreateProcessW(
				applicationName,   
				commandLine,       
				processAttributes, 
				threadAttributes,  
				inheritHandles,     
				creationFlags,     
				environment,       
				currentDirectory,  
				si,
				processInformation );

			return b;
		}

		delegate bool CreateProcessFn(
			IntPtr applicationName,   
			IntPtr commandLine,       
			IntPtr processAttributes, 
			IntPtr threadAttributes,  
			Int32  inheritHandles,       
			Int32  creationFlags,      
			IntPtr environment,       
			IntPtr currentDirectory,  
			IntPtr startupInfo,       
			IntPtr processInformation 
			);
	}
}
